const { secret } = require('../config/global');
// 导入jwt
const jwt = require('jsonwebtoken');
// 会员管理
const { getOne, add, update } = require('../utils/dbTools')
const { getBusinessInfo } = require('../model/business')

const tableName = 'member'
const businessTableName = 'business'



/**
 * 根据条件查询账号信息
 * @param {object} map 查询条件
*/
const getMemberInfo = async (map) => {
    if (!map) return false
    const result = await getOne(tableName, map)
    return result
}


/**
 * 根据账号id查询其他信息 
 * @param {number} id 账号id
 * @return {object} 账号其他信息
 */
const getMemberInfoById = async (id) => {
    if (!id) return false
    const result = await getMemberInfo({ id })
    return result
}

/***
 * 
 * 检测账号是否存在
 * @param {string} phone 手机号码
 * @return {boolean} true 表示手机号已存在, false 表示手机号不存在  
 */
const phoneIsExists = async (phone) => {
    const result = await getMemberInfo({ phone })
    const result2 = await getBusinessInfo({ phone })
    if (!result && !result2) {
        // 手机号码不存在
        return false
    }
    // 手机号码已存在
    return true
}

/**
 * 注册账号
 * @param {string} phone 手机号码
 * @param {number} account_type 账号类型( 1-普通账号 2-医护人员 3-医疗机构管理人员 ): 默认值为 2
 * @return {number} insertId 注册的账号id  
*/
const register = async (phone, account_type = 1) => {
    const baseData = { phone, account_type, name: phone }
    // 注册企业账号
    if (account_type == 3) {
        if (!await phoneIsExists(phone)) {
            const { insertId: bus_id } = await add({ phone }, businessTableName)
            baseData.bus_id = bus_id
        } else {
            const { id: bus_id } = await getBusinessInfo({ phone })
            baseData.bus_id = bus_id
        }
    }
    const { insertId } = await add(baseData, tableName)
    return insertId;
}

/**
 * 登录 
 * @param {string} phoneNumber 手机号码
 * @return {object} 账号信息
 */
const doLogin = async (phoneNumber) => {
    const result = await getOne(tableName, { phone: phoneNumber });
    if (result.status !== 1) { return { errorCode: 500, msg: '错误信息: 账号被冻结' } }
    const { id, account_type, phone, bus_id } = result
    // 企业账号:查询企业信息
    if (account_type > 1 && bus_id) {
        const businessInfo = await getBusinessInfo({ id: bus_id });
        result.businessInfo = businessInfo;
    }
    // 生成登录凭证token
    const token = jwt.sign({ id, account_type, phone }, secret, { expiresIn: '1h' });
    // 生成refresh_token
    const refresh_token = jwt.sign({ id, account_type, phone }, secret, { expiresIn: '2h' });
    return {
        ...result,
        token,
        refresh_token
    };
}


/**
 * 更新状态信息
 * @param {number} id 要更新的账号id
 * @param {object} fileds 要更新的字段  
 * */
const updateMember = async (id, fileds) => {
    if (!id) { return false }
    const result = await update({ id }, fileds, tableName)
    return result
}

/**
 * 根据账号id查询企业信息
 * 
*/

module.exports = {
    getMemberInfo,
    getMemberInfoById,
    phoneIsExists,
    register,
    doLogin,
    updateMember
}